﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.Mvc;
using AuditModel;
using AuditWeb.Models;
using System.IO;

namespace AuditWeb.Controllers
{ 
    public class ArchiveController : Controller
    {
        private AuditDBEntities db = new AuditDBEntities();
        IAnnualEventBL iaebl = new AnnualEventBL();
        IArchiveBL iabl = new ArchiveBL();

        //
        // GET: /Archive/
        [Authorize(Roles = "区县管理员")]
        public ViewResult Index(string id,string countycode,string subjectid, string archiveid)
        {
            string annualeventid = id;
            if (string.IsNullOrEmpty(id))
                annualeventid = iaebl.GetActiveEvents().FirstOrDefault().ID;
            
            countycode = countycode == null ? "" : countycode.Trim();
            //check the county code of logged user
            if(User.IsInRole("区县管理员"))
                countycode=HttpContext.Profile["CountyCode"].ToString();
            
            int _subjectid;
            int.TryParse(subjectid, out _subjectid);
            _subjectid=_subjectid<=0?-1:_subjectid;
            if (User.IsInRole("学科组组长"))
                _subjectid = (int)HttpContext.Profile["SubjectId"];

            archiveid = archiveid == null ? "" : archiveid.Trim();
            AdminArchiveModel aam = new AdminArchiveModel() { AnnualEventId = annualeventid, CountyCode = countycode, ArchiveId = archiveid, SubjctId = _subjectid, Date = DateTime.Now.Date };

            var archives = iabl.GetArchives(annualeventid, archiveid, _subjectid, countycode);//db.Archives.Include("AnnualEvent").Include("Subject").Include("County").Include("Teacher");
            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(annualeventid);
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.Archives = archives.ToList();
            var ccddates = from ccd in db.CountyClassDates where ccd.CountyCode == countycode select ccd.ClassDate;
            IList<string> dates=new List<string>();
            foreach(var cd in ccddates)
                dates.Add(cd.ToShortDateString());
            ViewBag.AvailableDates = new SelectList(dates);
            ViewBag.CountyName = db.Counties.SingleOrDefault(c => c.Code == countycode).Name;
            ViewBag.SubjectID = new SelectList(Helpers.GetActiveSubjects(annualeventid), "Id", "Name", _subjectid);
            //ViewBag.SubjectId = new SelectList(db.Subjects.ToList(), "Id", "Name");

            return View(aam);
        }

        //
        // GET: /Archive/Details/5
        [Authorize(Roles = "区县管理员")]
        public ViewResult Details(string id)
        {
            Archive archive = db.Archives.Single(a => a.ID == id);
            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(archive.AnnualEventID);
            ViewBag.AnnualEventId = archive.AnnualEventID;
            ViewBag.CountyName = db.Counties.SingleOrDefault(c => c.Code == archive.CountyCode).Name;
            return View(archive);
        }

        //
        // GET: /Archive/Create
        [Authorize(Roles = "区县管理员")]
        public ActionResult Create(string annualeventid)
        {
            //string annualeventid =eventid;
            //user's countycode
            ViewBag.AnnualEventIDList = new SelectList(iaebl.GetActiveEvents(), "ID", "Title",annualeventid);
            //var subjects=from s in db.Subjects 
            //             where (from c in db.CandidateQuotas select c.SubjectID).Contains(s.Id)
            //                 select s;

            ViewBag.SubjectID = new SelectList(Helpers.GetActiveSubjects(annualeventid), "Id", "Name");
            string countycode=HttpContext.Profile["CountyCode"].ToString();
            ViewBag.CountyCode = new SelectList(from c in db.Counties where c.Code == countycode select c, "Code", "Name", countycode);
            //ViewBag.TeacherID = new SelectList(db.Teachers, "Id", "Name");
            //maintain state
            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(annualeventid);
            ViewBag.AnnualEventId = annualeventid;
            var ccddates = from ccd in db.CountyClassDates where ccd.CountyCode == countycode select ccd.ClassDate;
            IList<string> dates = new List<string>();
            foreach (var cd in ccddates)
                dates.Add(cd.ToShortDateString());
            ViewBag.AvailableDates = new SelectList(dates);
            ViewBag.CountyName = db.Counties.SingleOrDefault(c => c.Code == countycode).Name;

            return View();
        } 

        //
        // POST: /Archive/Create
        [Authorize(Roles = "区县管理员")]
        [HttpPost]
        public ActionResult Create(Archive archive, HttpPostedFileBase photo, HttpPostedFileBase lessonplan, HttpPostedFileBase explanation)
        {
            if (ModelState.IsValid)
            {
                //db.Archives.AddObject(archive);
                //db.SaveChanges();
                if (archive.ClassDate != null)
                {
                    archive.EvaluationStartDate = archive.ClassDate;
                    archive.EvaluationDueDate = archive.ClassDate.Value.AddDays(2);
                }
                try
                {
                    iabl.Add(archive);
                    string aid = archive.ID;
                    archive = db.Archives.Single(a => a.ID == aid);
                    if (photo!=null&&photo.ContentLength > 0)
                    {
                        var fileName = archive.ID + Path.GetExtension(photo.FileName);
                        var path = Path.Combine(Server.MapPath("~/Content/attachments"), archive.AnnualEventID, archive.Subject.Name, archive.ID);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        path = Path.Combine(path, fileName);
                        archive.PhotoUrl = "~/Content/attachments/" + archive.AnnualEventID + "/" + archive.Subject.Name + "/" + archive.ID + "/" + fileName;
                        photo.SaveAs(path);
                    }
                    if (lessonplan!=null&&lessonplan.ContentLength > 0)
                    {
                        var fileName = AuditResources.Archive.Attachment1LessonPlan + Path.GetExtension(lessonplan.FileName);
                        var path = Path.Combine(Server.MapPath("~/Content/attachments"), archive.AnnualEventID, archive.Subject.Name,archive.ID);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        path = Path.Combine(path, fileName);
                        archive.Attachment1LessonPlan = fileName;
                        lessonplan.SaveAs(path);
                    }
                    if (explanation!=null&&explanation.ContentLength > 0)
                    {
                        var fileName = AuditResources.Archive.Attachment2Explanation+ Path.GetExtension(explanation.FileName);
                        var path = Path.Combine(Server.MapPath("~/Content/attachments"), archive.AnnualEventID, archive.Subject.Name, archive.ID);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        path = Path.Combine(path, fileName);
                        archive.Attachment2Explanation = fileName;
                        explanation.SaveAs(path);
                    }
                    db.SaveChanges();
                    return RedirectToAction("Index", new { id = archive.AnnualEventID });  
                }
                catch(Exception ex){
                    if (ex.Message == "CandidateQuotaExceeded!")
                    {
                        ModelState.AddModelError("Exceed", "超过名额限制！");
                    }
                    else
                    {
                        ModelState.AddModelError("Exceed", "暂时无法添加档案！");
                    }
                }
            }

            ViewBag.AnnualEventIDList = new SelectList(db.AnnualEvents, "ID", "Title", archive.AnnualEventID);
            //var subjects = from s in db.Subjects
            //               where (from c in db.CandidateQuotas select c.SubjectID).Contains(s.Id)
            //               select s;

            ViewBag.SubjectID = new SelectList(Helpers.GetActiveSubjects(archive.AnnualEventID), "Id", "Name", archive.SubjectID);
            //ViewBag.SubjectID = new SelectList(db.Subjects, "Id", "Name", archive.SubjectID);
            ViewBag.CountyCode = new SelectList(from c in db.Counties where c.Code == archive.CountyCode select c, "Code", "Name", archive.CountyCode);
            //ViewBag.TeacherID = new SelectList(db.Teachers, "Id", "Name", archive.TeacherID);
            var ccddates = from ccd in db.CountyClassDates where ccd.CountyCode == archive.CountyCode select ccd.ClassDate;
            IList<string> dates = new List<string>();
            foreach (var cd in ccddates)
                dates.Add(cd.ToShortDateString());
            ViewBag.AvailableDates = new SelectList(dates);

            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(archive.AnnualEventID);
            ViewBag.AnnualEventId = archive.AnnualEventID;

            ViewBag.CountyName = db.Counties.SingleOrDefault(c => c.Code == archive.CountyCode).Name;
            return View(archive);
        }
        
        //
        // GET: /Archive/Edit/5
 [Authorize(Roles = "区县管理员")]
        public ActionResult Edit(string id)
        {
            Archive archive = db.Archives.Single(a => a.ID == id);
            ViewBag.AnnualEventIDList = new SelectList(db.AnnualEvents, "ID", "Title", archive.AnnualEventID);

            ViewBag.SubjectID = new SelectList(Helpers.GetActiveSubjects(archive.AnnualEventID), "Id", "Name", archive.SubjectID);
            //ViewBag.SubjectID = new SelectList(db.Subjects, "Id", "Name", archive.SubjectID);
            ViewBag.CountyCode = new SelectList(from c in db.Counties where c.Code == archive.CountyCode select c, "Code", "Name", archive.CountyCode);
            //ViewBag.TeacherID = new SelectList(db.Teachers, "Id", "Name", archive.TeacherID);
            var ccddates = from ccd in db.CountyClassDates where ccd.CountyCode == archive.CountyCode select ccd.ClassDate;
            IList<string> dates = new List<string>();
            foreach (var cd in ccddates)
                dates.Add(cd.ToShortDateString());
            ViewBag.AvailableDates = new SelectList(dates);

            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(archive.AnnualEventID);
            ViewBag.AnnualEventId = archive.AnnualEventID;
            ViewBag.CountyName = db.Counties.SingleOrDefault(c => c.Code == archive.CountyCode).Name;
            return View(archive);
        }

        //
        // POST: /Archive/Edit/5
        [Authorize(Roles = "区县管理员")]
        [HttpPost]
        public ActionResult Edit(Archive archive,HttpPostedFileBase photo, HttpPostedFileBase lessonplan, HttpPostedFileBase explanation)
        {
            if (ModelState.IsValid)
            {
                db.Archives.Attach(archive);
                if (archive.ClassDate != archive.EvaluationStartDate)
                {
                    archive.EvaluationStartDate = archive.ClassDate;
                    archive.EvaluationDueDate = archive.ClassDate.Value.AddDays(2);
                }
                if (photo != null && photo.ContentLength > 0)
                {
                    var fileName = archive.ID + Path.GetExtension(photo.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/attachments"), archive.AnnualEventID, archive.Subject.Name, archive.ID);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    path = Path.Combine(path, fileName);
                    archive.PhotoUrl = "~/Content/attachments/" + archive.AnnualEventID + "/" + archive.Subject.Name + "/" + archive.ID+"/" + fileName;
                    photo.SaveAs(path);
                }
                if (lessonplan != null && lessonplan.ContentLength > 0)
                {
                    var fileName = AuditResources.Archive.Attachment1LessonPlan + Path.GetExtension(lessonplan.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/attachments"), archive.AnnualEventID, archive.Subject.Name, archive.ID);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    if (!string.IsNullOrEmpty(archive.Attachment1LessonPlan)&&System.IO.File.Exists(Path.Combine(path, archive.Attachment1LessonPlan)))
                    {
                        System.IO.File.Delete(Path.Combine(path, archive.Attachment1LessonPlan));
                    }
                    
                    path = Path.Combine(path, fileName);
                    archive.Attachment1LessonPlan = fileName;
                    lessonplan.SaveAs(path);
                }
                if (explanation != null && explanation.ContentLength > 0)
                {
                    var fileName = AuditResources.Archive.Attachment2Explanation + Path.GetExtension(explanation.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/attachments"), archive.AnnualEventID, archive.Subject.Name, archive.ID);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    if (!string.IsNullOrEmpty(archive.Attachment2Explanation) && System.IO.File.Exists(Path.Combine(path, archive.Attachment2Explanation)))
                    {
                        System.IO.File.Delete(Path.Combine(path, archive.Attachment2Explanation));
                    }

                    path = Path.Combine(path, fileName);
                    archive.Attachment2Explanation = fileName;
                    explanation.SaveAs(path);
                }
                db.ObjectStateManager.ChangeObjectState(archive, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index", new { id = archive.AnnualEventID });
            }
            ViewBag.AnnualEventIDList = new SelectList(db.AnnualEvents, "ID", "Title", archive.AnnualEventID);
            ViewBag.SubjectID = new SelectList(Helpers.GetActiveSubjects(archive.AnnualEventID), "Id", "Name", archive.SubjectID);
            ViewBag.CountyCode = new SelectList(from c in db.Counties where c.Code == archive.CountyCode select c, "Code", "Name", archive.CountyCode);
            //ViewBag.TeacherID = new SelectList(db.Teachers, "Id", "Name", archive.TeacherID);
            var ccddates = from ccd in db.CountyClassDates where ccd.CountyCode == archive.CountyCode select ccd.ClassDate;
            IList<string> dates = new List<string>();
            foreach (var cd in ccddates)
                dates.Add(cd.ToShortDateString());
            ViewBag.AvailableDates = new SelectList(dates);

            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(archive.AnnualEventID);
            ViewBag.AnnualEventId = archive.AnnualEventID;
            ViewBag.CountyName = db.Counties.SingleOrDefault(c => c.Code == archive.CountyCode).Name;
            return View(archive);
        }

        //
        // GET: /Archive/Delete/5
 [Authorize(Roles = "区县管理员")]
        public ActionResult Delete(string id, bool error)
        {
            Archive archive = db.Archives.Single(a => a.ID == id);
            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(archive.AnnualEventID);
            ViewBag.AnnualEventId = archive.AnnualEventID;
            ViewBag.CountyName = db.Counties.SingleOrDefault(c => c.Code == archive.CountyCode).Name;
            if (error)
            {
                ViewBag.Error = "此参赛档案已开始评分，无法完成删除操作！";
            }
            return View(archive);
        }

        //
        // POST: /Archive/Delete/5
        [Authorize(Roles = "区县管理员")]
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {            
            Archive archive = db.Archives.Single(a => a.ID == id);
            string annualeventid = archive.AnnualEventID;
            string countycode = archive.CountyCode;
            string subjectname = archive.Subject.Name;
            try
            {
                var alist = from a in db.Attachments where a.ArchiveID == id select a;
                foreach (Attachment a in alist)
                {
                    db.Attachments.DeleteObject(a);
                }
                db.SaveChanges();     
                db.Archives.DeleteObject(archive);
                db.SaveChanges();                
            }
            catch (Exception ex)
            {
                return RedirectToAction("Delete", new { id = id, error=true });
            }
            string path = Server.MapPath("~/Content/attachments/" + annualeventid + "/" + subjectname + "/" + id);
            if (Directory.Exists(path + "\\"))
            {
                Directory.Delete(path + "\\", true);
            }

            ViewBag.AnnualEvent = iaebl.GetAnnualEvent(annualeventid);
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.CountyName = db.Counties.SingleOrDefault(c => c.Code == countycode).Name;

            return RedirectToAction("Index", new { id = annualeventid });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}